package com.icoo.order.order.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.icoo.order.order.enums.OrderStatusEnum;
import com.icoo.order.order.mapper.OrderDetailMapper;
import com.icoo.order.order.mapper.OrderMapper;
import com.icoo.order.order.model.OrderVo;
import com.icoo.order.order.po.Order;
import com.icoo.order.order.po.OrderDetail;
import com.icoo.order.order.po.Product;
import com.icoo.order.order.service.OrderService;
import com.icoo.order.order.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired private ProductService productService;
    @Autowired private OrderDetailMapper orderDetailMapper;
    @Autowired private OrderMapper orderMapper;

    @Override
    @Transient
    public void createOrder(List<OrderVo> orderVos) {
        List<Integer> productIds = orderVos.stream().map(s -> s.getProductId()).distinct().collect(Collectors.toList());
        List<Product> products = productService.findByIds(productIds);
        Order order = new Order();
        order.setId(IdUtil.randomUUID());
        BigDecimal amount = new BigDecimal(0);

        for (OrderVo orderVo : orderVos) {
            for (Product product : products) {
                if(orderVo.getProductId().equals(product.getId()) &&
                    orderVo.getProductNum() != null &&
                    orderVo.getProductNum() != 0){

                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setOrderId(order.getId());
                    orderDetail.setProductId(product.getId());
                    orderDetail.setProductNum(orderVo.getProductNum());
                    orderDetail.setPrice(product.getPrice());
                    orderDetail.setCreateTime(new Date());
                    orderDetail.setUpdateTime(new Date());
                    orderDetailMapper.insert(orderDetail);
                    amount.add(product.getPrice().multiply(new BigDecimal(orderVo.getProductNum())));
                }
            }
        }

        order.setAmount(amount);
        order.setStatus(OrderStatusEnum.FINISHED.getCode());
        order.setUserId(Integer.valueOf(StpUtil.getLoginId().toString()));
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        orderMapper.insert(order);
    }
}
